//右侧抽屉页面
//  ZSBWorkOrderRightMenuView.m
//  HCNewGoldFinger
//
//  Created by hugh on 16/4/4.
//  Copyright © 2016年 zjhcsoftios. All rights reserved.
//

#import "ZSBWorkOrderRightMenuView.h"
#import "NSObject+MJKeyValue.h"
#import "iSeeNetworkRequest.h"
#import "UIColor+EX.h"
#import <SDWebImage/SDWebImage.h>
#import "NSBundle+AssociatedBundle.h"

#define ZSBWorkOrderRightMenuViewWidth    200

/***  屏幕宽 */
#define kScreenWidth  [[UIScreen mainScreen] bounds].size.width

/***  屏幕高度 */
#define kScreenHeight  [[UIScreen mainScreen] bounds].size.height

#define kFormat(string, args...)            [NSString stringWithFormat:string, args]

@interface ZSBWorkOrderRightMenuView()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic, strong) UIButton *handerView;

@property (nonatomic, strong) NSMutableArray *dateList;

@property (nonatomic, strong) UITableView *tableView;
@property(nonatomic,copy)NSString *datestr;


@end

@implementation ZSBWorkOrderRightMenuView

- (instancetype)init
{
    self = [super init];
    if (self) {
        self.frame = CGRectMake(kScreenWidth, 0, ZSBWorkOrderRightMenuViewWidth, kScreenHeight);
        self.backgroundColor = [UIColor whiteColor];

        [self setupView];
    }
    return self;
}

- (void)setupView
{        _dateList = [NSMutableArray array];

    _datestr =[self nowtime];

    _tableView= [[UITableView alloc] initWithFrame:CGRectMake(0, 0, ZSBWorkOrderRightMenuViewWidth, kScreenHeight) style:UITableViewStylePlain];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.autoresizingMask = ~UIViewAutoresizingNone;
    _tableView.backgroundView = nil;
    _tableView.backgroundColor = [UIColor clearColor];
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self addSubview:_tableView];
    
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ZSBWorkOrderRightMenuViewWidth, 25)];
    headerView.backgroundColor = [UIColor clearColor];
    _tableView.tableHeaderView = headerView;
}

- (void)show
{
    [_dateList removeAllObjects];
    if (_dateList == nil ||_dateList.count == 0) {
        [self getHomeEnterListMarket_head_all];
    }
    if (self.handerView == nil) {
        self.handerView = [UIButton buttonWithType:UIButtonTypeCustom];
        [_handerView setFrame:[UIScreen mainScreen].bounds];
        [_handerView setBackgroundColor:[UIColor colorWithRed:0 green:0 blue:0 alpha:0.3]];
        [_handerView addTarget:self action:@selector(dismiss) forControlEvents:UIControlEventTouchUpInside];
    }
    [_handerView addSubview:self];
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    
    [window addSubview:_handerView];
    
    
    [UIView animateWithDuration:0.25 animations:^{
        CGRect selfFrame = self.frame;
        selfFrame.origin.x = kScreenWidth - ZSBWorkOrderRightMenuViewWidth;
        self.frame = selfFrame;
    }];
    
}
//获取右边抽屉
- (void)getHomeEnterListMarket_head_all{

    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
    //订单请求
    if (_order) {
        [params setObject:@"market_right_trade" forKey:@"viewType"];
        [params setObject:@"true" forKey:@"includeTotal"];
    }else{
        //任务单请求
    [params setObject:@"market_right_order" forKey:@"viewType"];
        [params setObject:@"false" forKey:@"includeTotal"];

    }
    
    [iSeeNetworkRequest getWithHeaderUrl:kFormat(@"%@%@",NMarketMainUrl,GetHomeEnterStatus) params:params success:^(id object) {
        [self.dateList removeAllObjects];
        if (object[@"body"] && [object[@"body"] isKindOfClass:[NSDictionary class]]) {
            NSDictionary *body = object[@"body"];
            if (body[@"userInfos"] && [body[@"userInfos"] isKindOfClass:[NSArray class]]){
                NSArray *arr = body[@"userInfos"];
                
                for (NSMutableDictionary *dic in arr) {
                    ZPMenuModel *menumodel = [[ZPMenuModel alloc] init];
                    [menumodel setValuesForKeysWithDictionary:dic];
                    [self.dateList addObject:menumodel];
                }
            }
        }
        
        [self.tableView reloadData];

        if (!self.order) {
            [self getnumber];
        }
    } failure:^(NSError *error) {
        
    }];
}

- (void)dismiss
{
    [UIView animateWithDuration:0.3f animations:^{
        CGRect selfFrame = self.frame;
        selfFrame.origin.x = kScreenWidth;
        self.frame = selfFrame;
    } completion:^(BOOL finished) {
        [self.handerView removeFromSuperview];
    }];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 30;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    ZPMenuModel *menumodel =_dateList[section];
    if (menumodel.children.count) {
        return menumodel.children.count;
    }else{
        return 0;
    }
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return _dateList.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *cellName = @"cellName";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellName];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellName];
    }

    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(75, 0, 125, 30)];
    titleLabel.font = [UIFont systemFontOfSize:12];
    titleLabel.textColor = [UIColor colorWithHexString:@"333333"];
    titleLabel.backgroundColor = [UIColor clearColor];
    titleLabel.tag = 1002;
    [cell.contentView addSubview:titleLabel];
        

    UILabel *detailLabel = [[UILabel alloc] initWithFrame:CGRectMake(self.frame.size.width-40, 5, 30, 18)];
    titleLabel.font = [UIFont systemFontOfSize:10];
    titleLabel.textColor = [UIColor colorWithHexString:@"333333"];
    detailLabel.tag = 1003;
    detailLabel.layer.masksToBounds = YES;
    [detailLabel.layer setCornerRadius:4];
    NSBundle *bundle = [NSBundle bundleWithBundleName:@"NewMarketLib" podName:@"NewMarketLib"];
    detailLabel.backgroundColor = [UIColor colorWithPatternImage:[UIImage  imageNamed:@"info_btn_red" inBundle:bundle compatibleWithTraitCollection:nil]];
    detailLabel.textAlignment = NSTextAlignmentCenter;
    detailLabel.textColor = [UIColor whiteColor];
    
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(49, 7, 16, 16)];
    imageView.backgroundColor =[UIColor whiteColor];
    [cell.contentView addSubview:imageView];
    
    if (_dateList.count) {
        ZPMenuModel *menuview =_dateList[indexPath.section];

        if (menuview.children.count) {
            ZPMenuModel *model =menuview.children[indexPath.row];
        titleLabel.text =model.name;
            NSInteger abc = [model.total integerValue];
            [imageView sd_setImageWithURL:[NSURL URLWithString:kFormat(@"%@%@", NMarketMainUrl, model.iosIcon)]];
        if (abc == 0) {
            detailLabel.hidden = YES;
        }else{
            [cell.contentView addSubview:detailLabel];

            if ([model.total  intValue] > 99) {
                detailLabel.text = @"99+";
            }else{
                detailLabel.text =[NSString stringWithFormat:@"%@",model.total];
            }
        }
        }
    }
    
    return cell;
}
//section

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 44;
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
   
    UIView *headView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 44)];
    UITapGestureRecognizer *tap =[[UITapGestureRecognizer alloc] initWithTarget:self    action:@selector(sectiontap:)];
    [headView addGestureRecognizer:tap];
    headView.userInteractionEnabled = YES;
    headView.tag = section +1000;
    headView.backgroundColor = [UIColor whiteColor];
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(10, 10, 24, 24)];
    [headView addSubview:imageView];
    UILabel *titleLabel = [self labelWithFrame:CGRectMake(imageView.frame.size.width + imageView.frame.origin.x + 10, 0, 200, 44) font:[UIFont systemFontOfSize:14] textColor:[UIColor colorWithHexString:@"333333"]];
    [headView addSubview:titleLabel];
    //订单数量显示的header上面
    UILabel *detailLabel = [self labelWithFrame:CGRectMake(self.frame.size.width-40, 13, 30, 18) font:[UIFont systemFontOfSize:12] textColor:[UIColor colorWithHexString:@"333333"]];
    detailLabel.layer.masksToBounds = YES;
    [detailLabel.layer setCornerRadius:4];
    NSBundle *bundle = [NSBundle bundleWithBundleName:@"NewMarketLib" podName:@"NewMarketLib"];
    detailLabel.backgroundColor = [UIColor colorWithPatternImage:[UIImage  imageNamed:@"info_btn_red" inBundle:bundle compatibleWithTraitCollection:nil]];
    detailLabel.textAlignment = NSTextAlignmentCenter;
    detailLabel.textColor = [UIColor whiteColor];
    [headView addSubview:detailLabel];
    
    UIView *line = [[UIView alloc] initWithFrame:CGRectMake(0, 44-0.5, tableView.frame.size.width, 0.5)];
    line.backgroundColor = [UIColor colorWithHexString:@"cccccc"];
    [headView addSubview:line];
    
    if(_dateList.count){
    ZPMenuModel *model =  _dateList[section];
    [imageView sd_setImageWithURL:[NSURL URLWithString:kFormat(@"%@%@", NMarketMainUrl, model.iosIcon)]];
    imageView.backgroundColor =[UIColor whiteColor];
    titleLabel.text = model.name;
        
    //没有工单数量的时候不显示
    if ([model.total integerValue] == 0) {
        detailLabel.hidden = YES;
    }else{
        detailLabel.hidden = NO;
        if ([model.total intValue] > 99) {
            detailLabel.text = @"99+";
        }else{
        detailLabel.text =[NSString stringWithFormat:@"%@",model.total];
        }
    }
    }
    return headView;
}

//section点击事件
-(void)sectiontap:(UITapGestureRecognizer *)tap{
    UIView *view =tap.view;
    NSInteger tag =view.tag;
    if (self.clickBlock) {
        self.clickBlock(_dateList[tag - 1000]);
    }
    
    [self dismiss];
    
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if (self.clickBlock) {
        ZPMenuModel *model =_dateList[indexPath.section];
          ZPMenuModel *modela= model.children[indexPath.row];
        
        self.clickBlock(modela);
    }
    
    [self dismiss];
}
//获取抽屉条数
-(void)getnumber{
    
    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];

        //任务单
    [params setObject:@"market_right_order" forKey:@"viewType"];
    
    [iSeeNetworkRequest getWithHeaderUrl:kFormat(@"%@%@",NMarketMainUrl,ISEE_URL_GET_HOMEENTER_LISTNUMBER) params:params success:^(id object) {
        if (object[@"body"] && [object[@"body"] isKindOfClass:[NSDictionary class]]) {
            NSDictionary *body = object[@"body"];
            if (body[@"userInfos"] && [body[@"userInfos"] isKindOfClass:[NSArray class]]){
                NSArray *arr = body[@"userInfos"];
                for (NSMutableDictionary *dic in arr) {
                    for (int i = 0; i <self.dateList.count; i++) {
                        ZPMenuModel *menuview =self.dateList[i];
                        if ([menuview.logId integerValue]  == [dic[@"logId"] integerValue]) {
                            menuview.total = dic[@"total"] ;
                        }
                        for (int j = 0; j < menuview.children.count; j++) {
                            ZPMenuModel *model =menuview.children[j];
                            if ([model.logId integerValue]  == [dic[@"logId"] integerValue]) {
                                model.total = dic[@"total"] ;
                            }
                        }
                    }
                }
            }
        }
        
        [self.tableView reloadData];
//        [[MovementRecord shareRecord] addRecordWithCode:@"5231" andContent:@"nmarket/mobile/user/getHomeEnterTotal.action"   addstarttime:_datestr endtime:[MovementRecord nowtime]];
    } failure:^(NSError *error) {
        
    }];
    
}


- (UILabel *)labelWithFrame:(CGRect)frame font:(UIFont *)font textColor:(UIColor *)color
{
    UILabel *label = [[UILabel alloc] initWithFrame:frame];
    label.font = font;
    label.textColor = color;
    label.backgroundColor = [UIColor clearColor];
    //    label.autoresizingMask = UIViewAutoresizingFlexibleWidth;
    return label;
}



//获取当前时间
- (NSString *)nowtime{
    NSDate *date = [NSDate date];
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    
    
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    
    [formatter setDateFormat:@"YYYY-MM-dd hh:mm:ss:SSS"];
    NSString *datetime = [formatter stringFromDate:date];
    
    return datetime;
}


@end
